package com.example.springbootwebsocket.config;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: springboot-websocket
 * @description: session容器
 * @author: XianJin.Lu
 * @create: 2021-08-31 15:11
 **/
public class SessionPool {
    public static Map<String, Session>  sessions=new ConcurrentHashMap<>();

    public static void remove(String sessionId) throws IOException {
        for (String userId : sessions.keySet()) {
            Session session = sessions.get(userId);
            if(session.getId().equals(sessionId)){
                sessions.remove(userId);
                break;
            }
        }
    }

    //点对点发送
    public static void sendMessage(String sessionId,String message){
        sessions.get(sessionId).getAsyncRemote().sendText(message);
    }

    //群发
    public static void sendMessage(String message){
        for (String userId : sessions.keySet()) {
            sessions.get(userId).getAsyncRemote().sendText(message);
        }

    }

    public static void sendMessage(Map<String, Object> params) {
        //{"fromuserId":userId,"touserId":touserId,"msg":msg};
        String touserId = params.get("touserId").toString();
        String msg = params.get("msg").toString();
        String fromuserId = params.get("fromuserId").toString();
        msg="来自"+fromuserId+"的消息:"+msg;
        Session session = sessions.get(touserId);

        if(session!=null){
            //通过指定session消息单发
            session.getAsyncRemote().sendText(msg);
        }
    }
}
